var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var app = express();
var bodyParser = require("body-parser");

var {expressjwt:jwt} = require('express-jwt')
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(bodyParser.json({limit: "10mb", extended: true})); 
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//虚拟路由创建文件夹
app.use("/upload",express.static("upload"))
app.use(cors())
// app.use(
//   jwt({
//     secret: "lin",
//     algorithms: ["HS256"],
//   }).unless({
//     path: ["/zjb/login", "/zjb/pclogin","/zhy/send",'/zhy/upload',{url:/^\/upload/,methods:["GET"]}],
//   })
// );

var zjb_Router = require('./routes/zjb');
var yzb_Router = require('./routes/yzb');
var cxy_Router = require('./routes/cxy');
var zyh_Router = require('./routes/zhy');

//上传文件（图片，语音，视频等）
var fileRouter = require('./routes/files')

app.use('/zjb', zjb_Router);
app.use('/yzb', yzb_Router);
app.use('/zhy', zyh_Router);
app.use('/cxy', cxy_Router);

//yzb
app.use('/flies',fileRouter)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


/**
 * WebSocket模块
 */

const { WebSocketServer } = require('ws');
const server = new WebSocketServer({ port: 8082 });
// 存储聊天信息
let chatInfo = []
// 存储在线用户
let onlineUser = []
server.on("connection", (socket, req, res) => {
  console.log('链接成功');
  // 用户注册
  // 获取当前连接websocket的用户uid
  let uid = req.url.substr(1)
  socket["id"] = uid
  let index = onlineUser.findIndex(val => val.id === uid)

  if (index == -1) {
    onlineUser.push(socket)
  }

  // 从客户端接收消息
  socket.on("message", (data) => {
    // 将收到的消息转成对象格式
    let msg = data.toString()
    let message = JSON.parse(msg)
    // console.log(message, '123456789');
    // 通知当前用户消息发送成功
    socket.send(JSON.stringify({
      message: message.message,
      types: message.types,
      toid: message.fid,
      tip: 0
    }))
    // 存储当前用户发送的数据
    chatInfo.push({
      from: uid,
      to: message.fid,
      message: message.message,
      types: message.types
    })
    // console.log(onlineUser);

    // 根据fid匹配到接收消息的用户并发送通知
    onlineUser.forEach(item => {
      if (item.id == message.fid) {
        console.log("发送消息成功");
        item.send(JSON.stringify({
          message: message.message,
          types: message.types,
          from: uid,
          tip: 1
        }))
      }
    })
  });



  // 连接关闭后清除在线用户
  socket.on('close', res => {
    let newUserArr = []
    let newUserIds = []
    for (let i = 0; i < onlineUser.length; i++) {
      let val = onlineUser[i]
      if (val.id !== uid) {
        newUserArr.push(val)
        newUserIds.push(val.id)
      }
    }
    onlineUser = newUserArr
    let User = JSON.stringify({
      onlineUser: newUserIds,
      type: 'users'
    })
    onlineUser.forEach((client) => client.websocket.send(User))
    console.log('用户离开了');
  })

  socket.send(JSON.stringify({
    msg: '连接已建立',
    type: 'system'
  }))
});


module.exports = app;
